package com.huxiu;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.huxiu.net.GsonRequest;
import com.huxiu.net.NetworkConstants;
import com.huxiu.net.model.ArticleContent;
import com.huxiu.net.responses.ArticlebyIdResponse;
import com.huxiu.utils.Constants;
import com.huxiu.utils.ErrorResponseException;
import com.huxiu.utils.JavaScriptinerface;
import com.huxiu.utils.Loading;
import com.huxiu.utils.NetUtil;
import com.huxiu.utils.Settings;
import com.huxiu.utils.UmenEvent;
import com.huxiu.utils.Utils;
import com.huxiu.view.ArticleWebView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.analytics.MobclickAgent;

import java.util.LinkedHashMap;
import java.util.Map;

public class DetailActivity extends BaseActivity implements ArticleWebView.ArticleWebViewListener {
    //Tag
    private static final String TAG = DetailActivity.class.getName();
    @ViewInject(R.id.webview)
    private ArticleWebView webview;

    @ViewInject(R.id.bottom_bar)
    private LinearLayout bottom_bar;
    @ViewInject(R.id.layout_back)
    private RelativeLayout layout_back;

    @ViewInject(R.id.text_comment)
    private TextView text_comment;

    @ViewInject(R.id.layout_comment)
    private RelativeLayout layout_comment;

    @ViewInject(R.id.text_commment_num)
    private TextView text_commment_num;

    @ViewInject(R.id.layout_comment_num)
    private RelativeLayout layout_comment_num;


    @ViewInject(R.id.layout_share)
    private RelativeLayout layout_share;

    private String h5_url;

    private TextView titleView;

    private Thread mThread;

    private ArticleContent mArticleContent;

    private DetailActivity instance;

    private Handler mHandler = new Handler();

    private JavaScriptinerface mJavaScriptinerface;

    @ViewInject(R.id.loading_view)
    private View loading_view;

    private Handler handler;
    private Runnable runnable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        instance = this;
        ViewUtils.inject(this);
        Loading.showLoading(instance);
        init();
        initdata();
    }

    private void init() {
        handler = new Handler();
        runnable = new Runnable() {
            @Override
            public void run() {
                Utils.showToast(R.string.generic_failure);
                reLoadView.setVisibility(View.VISIBLE);
                Loading.closeLoading();
            }
        };
        handler.postDelayed(runnable, Constants.TIME_RELOADE);
        if (mArticleContent == null) {
            if (getIntent().hasExtra(Constants.TUIJIAN_ITEM_KEY)) {
                String data = getIntent().getStringExtra(Constants.TUIJIAN_ITEM_KEY);
                mArticleContent = new Gson().fromJson(data, ArticleContent.class);
                h5_url = mArticleContent.h5_url;
            } else if (getIntent().hasExtra(Constants.COMMENT_ITEM_KEY)) {
                String data = getIntent().getStringExtra(Constants.COMMENT_ITEM_KEY);
                mArticleContent = new Gson().fromJson(data, ArticleContent.class);
                h5_url = mArticleContent.h5_url;
            } else if (getIntent().hasExtra(Constants.ARTICLE_ID_KEY)) {
                mArticleContent = new ArticleContent();
                mArticleContent.aid = getIntent().getStringExtra(Constants.ARTICLE_ID_KEY);
            } else if (getIntent().hasExtra(Constants.PUSH_ID_KEY)) {
                mArticleContent = new ArticleContent();
                mArticleContent.aid = getIntent().getStringExtra(Constants.PUSH_ID_KEY);
            }
        }
        IntentFilter intent = new IntentFilter();
        intent.addAction(Constants.INTENT_ARTICLE_COMMENT_SUCCESS);
        LocalBroadcastManager.getInstance(APP.getInstance()).registerReceiver(mReceiver, intent);
    }

    private void initdata() {
        if (!NetUtil.checkNet(instance)) {
            Utils.showToast(R.string.generic_check);
            reLoadView.setVisibility(View.VISIBLE);
            Loading.closeLoading();
            return;
        }
        get_article_by_aid();
    }

    private void initweb() {
        mJavaScriptinerface = new JavaScriptinerface(instance, mArticleContent, webview);
        updateWebViewSettings(webview);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.addJavascriptInterface(mJavaScriptinerface, "android");
        webview.setWebViewClient(new webviewClient());
        webview.loadUrl(mArticleContent.h5_url);
        //        webview.loadUrl("file:///android_asset/index.html");
    }


    //广播接收者
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, final Intent intent) {
            String action = intent.getAction();
            if (action.equals(Constants.INTENT_ARTICLE_COMMENT_SUCCESS)) {
                webview.reload();
                text_commment_num.setText(mArticleContent.commentnum+1+"");
            }

        }
    };


    class webviewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Uri uri = Uri.parse(url);
            if (Utils.isHuxiuArticleUrl(uri)) {
                UmenEvent.UmengEventMap(instance, UmenEvent.APP_ARTICLE_CONTENT, UmenEvent.ARTICLE_DETAIL_RELATE_ARTICLE);
                Intent intent = Utils.getArticleIntentFromUri(DetailActivity.this, uri);
                startActivity(intent);
            } else if (Utils.isHuxiuCommentUrl(uri)) {
                //                launchComments(Long.parseLong(uri.getPathSegments().get(1)), "");
            } else {
                Intent intent = new Intent(DetailActivity.this, BrowserActivity.class);
                intent.putExtra("url", url);
                startActivity(intent);
            }
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            Loading.closeLoading();
            loading_view.setVisibility(View.GONE);
            mJavaScriptinerface.webviewui();
            bottom_bar.setVisibility(View.VISIBLE);
            handler.removeCallbacks(runnable);
        }
    }

    @OnClick({R.id.layout_back, R.id.layout_share, R.id.layout_comment, R.id.reLoadView})
    public void mOnClick(View v) {
        switch (v.getId()) {
            case R.id.layout_back:
                if (webview.canGoBack()) {
                    webview.goBack();
                } else {
                    DetailActivity.this.finish();
                }

                break;
            case R.id.layout_share:
                new AsyncTask<Void, Void, Void>() {
                    Bitmap bmp = null;

                    @Override
                    protected Void doInBackground(Void... params) {
                        bmp = ImageLoader.getInstance().loadImageSync(mArticleContent.pic_path + Constants.IMAGE_WEBP);
                        //                        bmp = ImageLoader.getInstance().loadImageSync("https://gd2.alicdn.com/bao/uploaded/i2/TB1uH32KpXXXXcqXFXXXXXXXXXX_!!0-item_pic.jpg");
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void aVoid) {
                        super.onPostExecute(aVoid);
                        Utils.launchShareActivity(instance,
                                mArticleContent.title, mArticleContent.h5_url,
                                mArticleContent == mArticleContent ? "doc" : "topic", mArticleContent.pic_path + Constants.IMAGE_WEBP,
                                Utils.SubString(mArticleContent.summary), bmp, UmenEvent.ARTICLE_SHARE);
                    }
                }.execute();
                break;
            case R.id.layout_comment:
                UmenEvent.UmengEventMap(instance, UmenEvent.APP_ARTICLE_CONTENT, UmenEvent.ARTICLE_DETAIL_ENTER_COMMENT_BOTTOM);
                Intent intent = new Intent(instance, CommentActivity.class);
                intent.putExtra(Constants.ARTICLE_ID_KEY, mArticleContent.aid);
                startActivity(intent);
                break;
            case R.id.reLoadView:
                reLoadView.setVisibility(View.GONE);
                Loading.showLoading(instance);
                initdata();
                break;
        }
    }

    @Override
    public void onScrollOverOneScreen() {
    }

    @Override
    public void onScrollLessThanOneScreen() {

    }


    //点赞功能
    private void get_article_by_aid() {
        String url = NetworkConstants.GET_ARTICLE_BY_AID_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("aid", mArticleContent.aid);
        GsonRequest<ArticlebyIdResponse> request = new GsonRequest<>(url, Request.Method.POST,
                ArticlebyIdResponse.class, true, params, new Response.Listener<ArticlebyIdResponse>
                () {
            @Override
            public void onResponse(ArticlebyIdResponse response) {
                if (response.isSuccess()) {
                    mArticleContent = response.data;
                    initweb();
                    UiChange();
                } else {
                    Utils.showToast(response.error.message);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                reLoadView.setVisibility(View.VISIBLE);
                Loading.closeLoading();
                Throwable t = error.getCause();
                if (t instanceof ErrorResponseException) {
                    Log.e("params", "message" + error.getMessage().toString());
                    //                Utils.showToast(error.getMessage());
                } else {
                    Utils.showToast(R.string.generic_failure);
                }
            }
        });
        BaseActivity.getmQueue().add(request);
    }

    public void UiChange() {
        if (mArticleContent.commentnum == 0) {
            layout_comment_num.setVisibility(View.GONE);
        } else {
            layout_comment_num.setVisibility(View.VISIBLE);
            text_commment_num.setText(mArticleContent.commentnum + "");
        }
    }


    @OnClick(R.id.text_comment)
    public void writeComment(View v) {
        if (!Settings.isLoggedIn()) {
            Utils.askLogIn(instance);
            return;
        }
        UmenEvent.UmengEventMap(instance, UmenEvent.APP_ARTICLE_CONTENT, UmenEvent.ARTICLE_DETAIL_SEND_COMMENT);
        Intent intent = new Intent(this, SubmitCommentActivity.class);
        intent.putExtra(Constants.ARTICLE_ID_KEY, mArticleContent.aid);
        intent.putExtra("type_article", "add_post");
        intent.putExtra(UmenEvent.COMMENT_INTENT_KEY, UmenEvent.ARTICLE_DETAIL_SEND_COMMENT);
        this.startActivity(intent);
        this.overridePendingTransition(R.anim.activity_open, 0);
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("SplashScreen");
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("SplashScreen");
        MobclickAgent.onPause(this);
    }

}
